package com.example.pathtracker.utils

import android.content.Context
import android.net.ConnectivityManager
import android.net.NetworkCapabilities
import android.util.Log
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.io.IOException
import java.net.HttpURLConnection
import java.net.URL

object NetworkUtils {
    
    fun isNetworkAvailable(context: Context): Boolean {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val network = connectivityManager.activeNetwork ?: return false
        val activeNetwork = connectivityManager.getNetworkCapabilities(network) ?: return false
        
        return when {
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> true
            activeNetwork.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> true
            else -> false
        }
    }
    
    suspend fun testServerConnection(url: String): Boolean = withContext(Dispatchers.IO) {
        try {
            val connection = URL(url).openConnection() as HttpURLConnection
            connection.requestMethod = "GET"
            connection.connectTimeout = 5000
            connection.readTimeout = 5000
            
            val responseCode = connection.responseCode
            Log.d("NetworkUtils", "服务器连接测试: $url, 响应码: $responseCode")
            
            connection.disconnect()
            responseCode in 200..299
        } catch (e: IOException) {
            Log.e("NetworkUtils", "服务器连接失败: $url", e)
            false
        }
    }
    
    fun logNetworkInfo(context: Context) {
        val connectivityManager = context.getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val network = connectivityManager.activeNetwork
        val networkCapabilities = connectivityManager.getNetworkCapabilities(network)
        
        Log.d("NetworkUtils", "网络信息:")
        Log.d("NetworkUtils", "  - 网络: $network")
        Log.d("NetworkUtils", "  - 网络能力: $networkCapabilities")
        Log.d("NetworkUtils", "  - WiFi: ${networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)}")
        Log.d("NetworkUtils", "  - 移动网络: ${networkCapabilities?.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR)}")
    }
} 